﻿using System;
using System.Linq;
using System.Web.UI.WebControls;
using Emporium_Web.Controls;
using Emporium_Web.Enums;
using Emporium_Web.DBML;
using System.Linq.Expressions;

namespace Emporium_Web
{
    public partial class ClienteList : System.Web.UI.Page
    {
        public string SortExpression
        {
            get
            {
                return ViewState["gv_SortExpression"] == null ? "" : ViewState["gv_SortExpression"].ToString();
            }
            set
            {
                ViewState["gv_SortExpression"] = value;
            }
        }

        public string SortDirection
        {
            get
            {
                return ViewState["gv_SortDirection"] == null ? "" : ViewState["gv_SortDirection"].ToString();
            }
            set
            {
                ViewState["gv_SortDirection"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    Master.ActualizaMenu(MenuPrincipal.Generales, (int)MenuGenerales.Cliente);
                    Master.AgregarBreadcrumb("Clientes", "#", true);
                    Master.AgregarBreadcrumb("Listado", "ClienteList.aspx", false);
                    warningMessage.Visible = false;
                    errorMessage.Visible = false;
                    ListarClientes();
                }
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        protected void btnBuscar_Click(object sender, EventArgs e)
        {
            try
            {
                ListarClientes();
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        protected void btnAdicionar_Click(object sender, EventArgs e)
        {
            Response.Redirect("ClienteForm.aspx");
        }

        protected void btnModificar_Click(object sender, EventArgs e)
        {
            try
            {
                int codigo = 0;
                if (Int32.TryParse(hdnSeleccion.Value.ToString(), out codigo))
                {
                    Response.Redirect("ClienteForm.aspx?Operacion=" + (int)AccionesForm.Modificar + "&ClienteId=" + codigo);
                }
                else
                {
                    warningMessage.Visible = true;
                    lblWarningMessage.Text = Resources.MensajesValidacion.NoItemSelected;
                }
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        protected void btnConsultar_Click(object sender, EventArgs e)
        {
            try
            {
                int codigo = 0;
                if (Int32.TryParse(((LinkButton)sender).Text, out codigo))
                {
                    Response.Redirect("ClienteForm.aspx?Operacion=" + (int)AccionesForm.Consultar + "&ClienteId=" + codigo);
                }
                else
                {
                    warningMessage.Visible = true;
                    lblWarningMessage.Text = Resources.MensajesValidacion.NoItemSelected;
                }
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        protected void btnEliminar_Click(object sender, EventArgs e)
        {
            try
            {
                Eliminar();
                ListarClientes();
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        protected void gvPagerPageChanged(object sender, DataNavigatorEventArgs e)
        {
            try
            {
                ListarClientes();
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        protected void gvClientes_Sorting(object sender, GridViewSortEventArgs e)
        {
            try
            {
                if (this.SortExpression != null && this.SortExpression.Equals(e.SortExpression))
                {
                    this.SortDirection = this.SortDirection.ToUpper().Equals("ASC") ? "DES" : "ASC";
                }
                else
                {
                    this.SortDirection = e.SortDirection.ToString().Substring(0, 3);
                }

                this.SortExpression = e.SortExpression;

                ListarClientes();
            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        protected void gvClientes_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                if (gvClientes.HeaderRow == null)
                {
                    return;
                }

                this.SortExpression = e.CommandArgument != null ? e.CommandArgument.ToString() : "Id";
                this.SortDirection = e.CommandName.Equals("SortUp") ? "ASC" : "DES";
                
                ListarClientes();

            }
            catch (Exception x)
            {
                lblErrorMessage.Text = x.Message;
                errorMessage.Visible = true;
            }
        }

        private void ActivaIconoOrdenamiento() 
        {
            if (gvClientes.HeaderRow == null)
            {
                return;
            }

            if (this.SortDirection != null && this.SortDirection.ToUpper().Equals("ASC"))
            {
                LinkButton lnkSender = (LinkButton)gvClientes.HeaderRow.FindControl("lnkSortUp" + this.SortExpression);
                LinkButton lnkSortDown = (LinkButton)gvClientes.HeaderRow.FindControl(lnkSender.ID.Replace("SortUp", "SortDown"));
                lnkSortDown.CssClass = "sort-down";
                lnkSender.CssClass = "sort-up active";
            }
            else
            {
                LinkButton lnkSender = (LinkButton)gvClientes.HeaderRow.FindControl("lnkSortDown" + this.SortExpression);
                LinkButton lnkSortUp = (LinkButton)gvClientes.HeaderRow.FindControl(lnkSender.ID.Replace("SortDown", "SortUp"));
                lnkSortUp.CssClass = "sort-up";
                lnkSender.CssClass = "sort-down active";
            }
        }

        private void ListarClientes()
        {
            TablasDataContext database = new TablasDataContext();

            var listarQuery = from clientes in database.TG_Cliente
                              where (txtNumero.Text.Trim() == "" || clientes.Numero == txtNumero.Text.Trim())
                              && (txtNombre.Text.Trim() == "" || clientes.Nombre.Contains(txtNombre.Text.Trim()))
                              select clientes;

            listarQuery = OrdenarQuery(listarQuery);

            gvClientes.DataSource = listarQuery.Skip((gvPager.CurrentPage - 1) * gvPager.PageSize).Take(gvPager.PageSize).ToList();
            gvClientes.DataBind();

            int totalReg = listarQuery.Count();

            if (totalReg > 0)
            {
                gvClientes.UseAccessibleHeader = false;
                gvClientes.HeaderRow.TableSection = TableRowSection.TableHeader;
                gvPager.Visible = true;
                gvPager.TotalRowCount = totalReg;
                warningMessage.Visible = false;
            }
            else
            {
                lblWarningMessage.Text = Resources.MensajesValidacion.NoDataFound;
                warningMessage.Visible = true;
                gvPager.Visible = false;
            }

            lblMensajeGridFooter.Text = String.Format(Resources.MensajesValidacion.GridFooterMessage, totalReg);
            ActivaIconoOrdenamiento();
        }

        private IQueryable<TG_Cliente> OrdenarQuery(IQueryable<TG_Cliente> listarQuery)
        {
            if (this.SortExpression == null || this.SortExpression.Trim().Equals(""))
            {
                this.SortExpression = "Id";
            }

            if (this.SortDirection == null || this.SortDirection.Trim().Equals(""))
            {
                this.SortDirection = "DES";
            }

            if (this.SortExpression == "Id")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.Id);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.Id);
                }
            }
            else if (this.SortExpression == "Nombre")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.Nombre);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.Nombre);
                }
            }
            else if (this.SortExpression == "Email")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.Email);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.Email);
                }
            }
            else if (this.SortExpression == "Movil")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.Movil);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.Movil);
                }
            }
            else if (this.SortExpression == "Numero")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.Numero);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.Numero);
                }
            }
            else if (this.SortExpression == "Origen")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.Origen);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.Origen);
                }
            }
            else if (this.SortExpression == "Telefono")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.Telefono);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.Telefono);
                }
            }
            else if (this.SortExpression == "Tipo")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.Tipo);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.Tipo);
                }
            }
            else if (this.SortExpression == "Contacto")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.Contacto);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.Contacto);
                }
            }
            else if (this.SortExpression == "Web")
            {
                if (this.SortDirection.ToUpper().Equals("ASC"))
                {
                    listarQuery = listarQuery.OrderBy(c => c.Web);
                }
                else
                {
                    listarQuery = listarQuery.OrderByDescending(c => c.Web);
                }
            }
            return listarQuery;
        }

        private void Eliminar()
        {
            int id = 0;
            if (Int32.TryParse(hdnSeleccion.Value.ToString(), out id))
            {
                TablasDataContext database = new TablasDataContext();

                var cliente = (from clientes in database.TG_Cliente
                               where clientes.Id == id
                               select clientes).First();

                if (cliente != null)
                {
                    database.TG_Cliente.DeleteOnSubmit(cliente);

                    foreach (var item in cliente.TG_ClienteDireccion)
                    {
                        database.TG_ClienteDireccion.DeleteOnSubmit(item);
                    }

                    database.SubmitChanges();
                }

                hdnSeleccion.Value = "";
            }
            else
            {
                warningMessage.Visible = true;
                lblWarningMessage.Text = Resources.MensajesValidacion.NoItemSelected;
            }
        }
    }
}